package org.soc.timesheet.controller;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.soc.timesheet.domain.UsersProject;
import org.soc.timesheet.server.domain.service.ProjectsService;
import org.soc.timesheet.server.domain.service.SubProjectsService;
import org.soc.timesheet.server.domain.service.UsersProjectService;
import org.soc.timesheet.server.domain.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;
import org.springframework.roo.addon.web.mvc.controller.json.RooWebJson;

@RequestMapping("/usersprojects")
@Controller
@RooWebScaffold(path = "usersprojects", formBackingObject = UsersProject.class)
@RooWebJson(jsonObject = UsersProject.class)
public class UsersProjectController {
	
	@RequestMapping(value="/subproject/{id}")
	@ResponseBody
	public ResponseEntity<List<UsersProject>> findByIdSubProjects(@PathVariable(value="id") int idSubproject, HttpServletRequest request,HttpServletResponse response){
		List<UsersProject> ups = usersProjectService.findByIdSubProject(idSubproject);
		
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/json");
		return new ResponseEntity<List<UsersProject>>(ups,headers, (ups==null || ups.size()==0?HttpStatus.NO_CONTENT:HttpStatus.FOUND));
				
		
		
	}

	@Autowired
    UsersProjectService usersProjectService;

	@Autowired
    ProjectsService projectsService;

	@Autowired
    SubProjectsService subProjectsService;

	@Autowired
    UsersService usersService;

	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid UsersProject usersProject, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, usersProject);
            return "usersprojects/create";
        }
        uiModel.asMap().clear();
        usersProjectService.saveUsersProject(usersProject);
        return "redirect:/usersprojects/" + encodeUrlPathSegment(usersProject.getId().toString(), httpServletRequest);
    }

	@RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
        populateEditForm(uiModel, new UsersProject());
        return "usersprojects/create";
    }

	@RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") String id, Model uiModel) {
        uiModel.addAttribute("usersproject", usersProjectService.findUsersProject(id));
        uiModel.addAttribute("itemId", id);
        return "usersprojects/show";
    }

	@RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, @RequestParam(value = "sortFieldName", required = false) String sortFieldName, @RequestParam(value = "sortOrder", required = false) String sortOrder, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("usersprojects", UsersProject.findUsersProjectEntries(firstResult, sizeNo, sortFieldName, sortOrder));
            float nrOfPages = (float) usersProjectService.countAllUsersProjects() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("usersprojects", UsersProject.findAllUsersProjects(sortFieldName, sortOrder));
        }
        return "usersprojects/list";
    }

	@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid UsersProject usersProject, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, usersProject);
            return "usersprojects/update";
        }
        uiModel.asMap().clear();
        usersProjectService.updateUsersProject(usersProject);
        return "redirect:/usersprojects/" + encodeUrlPathSegment(usersProject.getId().toString(), httpServletRequest);
    }

	@RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") String id, Model uiModel) {
        populateEditForm(uiModel, usersProjectService.findUsersProject(id));
        return "usersprojects/update";
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") String id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        UsersProject usersProject = usersProjectService.findUsersProject(id);
        usersProjectService.deleteUsersProject(usersProject);
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/usersprojects";
    }

	void populateEditForm(Model uiModel, UsersProject usersProject) {
        uiModel.addAttribute("usersProject", usersProject);
        uiModel.addAttribute("projectses", projectsService.findAllProjectses());
        uiModel.addAttribute("subprojectses", subProjectsService.findAllSubProjectses());
        uiModel.addAttribute("userses", usersService.findAllUserses());
    }

	String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<String> showJson(@PathVariable("id") String id) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        try {
            UsersProject usersProject = usersProjectService.findUsersProject(id);
            if (usersProject == null) {
                return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity<String>(usersProject.toJson(), headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<String> listJson() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        try {
            List<UsersProject> result = usersProjectService.findAllUsersProjects();
            return new ResponseEntity<String>(UsersProject.toJsonArray(result), headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
    public ResponseEntity<String> createFromJson(@RequestBody String json, UriComponentsBuilder uriBuilder) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        try {
            UsersProject usersProject = UsersProject.fromJsonToUsersProject(json);
            usersProjectService.saveUsersProject(usersProject);
            RequestMapping a = (RequestMapping) getClass().getAnnotation(RequestMapping.class);
            headers.add("Location",uriBuilder.path(a.value()[0]+"/"+usersProject.getId().toString()).build().toUriString());
            return new ResponseEntity<String>(headers, HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(value = "/jsonArray", method = RequestMethod.POST, headers = "Accept=application/json")
    public ResponseEntity<String> createFromJsonArray(@RequestBody String json) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        try {
            for (UsersProject usersProject: UsersProject.fromJsonArrayToUsersProjects(json)) {
                usersProjectService.saveUsersProject(usersProject);
            }
            return new ResponseEntity<String>(headers, HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, headers = "Accept=application/json")
    public ResponseEntity<String> updateFromJson(@RequestBody String json, @PathVariable("id") String id) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        try {
            UsersProject usersProject = UsersProject.fromJsonToUsersProject(json);
            usersProject.setId(id);
            if (usersProjectService.updateUsersProject(usersProject) == null) {
                return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity<String>(headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
    public ResponseEntity<String> deleteFromJson(@PathVariable("id") String id) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        try {
            UsersProject usersProject = usersProjectService.findUsersProject(id);
            if (usersProject == null) {
                return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
            }
            usersProjectService.deleteUsersProject(usersProject);
            return new ResponseEntity<String>(headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
